package com.wangsd.web.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wangsd.common.basicbean.Result;
import com.wangsd.common.utils.HttpClientUtils;
import com.wangsd.common.utils.PayUtil;
import com.wangsd.web.face.entity.DisGit;
import com.wangsd.web.face.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Api(value = "disgit", tags = "扫码押金冻结")
@Controller
@RequestMapping("/api/disgit")
@Slf4j
public class DisgitController {

    @Value("${service.url}")
    private String serviceUrl;

    @Autowired
    MemberService memberService;

    @ApiOperation(value = "扫码押金冻结首页", notes = "扫码押金冻结首页", httpMethod = "POST")
    @RequestMapping(value = "/getCodeUrl", method = RequestMethod.POST)
    @ResponseBody
    public Object getCodeUrl(@ApiParam(name = "params", value = "传入json格式") DisGit params) {
        Map<String, String> map = new HashMap<>();
        StringBuilder codeUrl = new StringBuilder();
        codeUrl.append(serviceUrl).append("/api/disgit/index?")
                .append("authen_code=").append(params.getAuthen_code())
                .append("&pay_platform=").append(params.getPay_platform())
                .append("&out_shop_id=").append(params.getOut_shop_id())
                .append("&out_sub_mch_id=").append(params.getOut_sub_mch_id())
                .append("&out_mch_id=").append(params.getOut_mch_id())
                .append("&author_code=").append(params.getAuthor_code())
                .append("&out_freeze_no=").append(params.getOut_freeze_no())
                .append("&freeze_fee=").append(params.getFreeze_fee())
                .append("&device_id=").append(params.getDevice_id())
                .append("&storeName=").append(params.getStoreName());
        map.put("codeUrl", codeUrl.toString());
        return map;
    }

    @ApiOperation(value = "扫码押金冻结首页", notes = "扫码押金冻结首页", httpMethod = "GET")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public Object index(String authen_code, Integer pay_platform, String out_shop_id,
                        String out_sub_mch_id, String out_mch_id, String author_code,
                        String out_freeze_no, Integer freeze_fee, String device_id,
                        String storeName,
                        Model model) {
        Map<String, Object> map = new HashMap<>();
        map.put("authen_code", authen_code);
        map.put("pay_platform", pay_platform);
        map.put("out_shop_id", out_shop_id);
        map.put("out_sub_mch_id", out_sub_mch_id);
        map.put("out_mch_id", out_mch_id);
        map.put("author_code", author_code);
        map.put("out_freeze_no", out_freeze_no);
        map.put("freeze_fee", freeze_fee);
        map.put("device_id", device_id);
        map.put("storeName", storeName);
        model.addAttribute("params", map);
        return "disgit";
    }

    @ApiOperation(value = "扫码押金冻结操作", notes = "扫码押金冻结操作", httpMethod = "POST")
    @RequestMapping(value = "/disgitControl", method = RequestMethod.POST)
    @ResponseBody
    public Object disgitControl(HttpServletRequest request, @ApiParam(name = "params", value = "传入json格式") DisGit params) {
        String ipAddr = PayUtil.getIpAddr(request);

        JSONObject paramObject = new JSONObject();

        JSONObject authenInfoObject = new JSONObject();
        JSONObject aObject = new JSONObject();
        aObject.put("authen_type",1);
        aObject.put("authen_code",params.getAuthen_code());
        authenInfoObject.put("a",aObject);

        paramObject.put("authen_info",JSON.toJSONString(authenInfoObject));

        JSONObject request_content = new JSONObject();
        JSONObject pay_mch_key = new JSONObject();
        pay_mch_key.put("pay_platform",params.getPay_platform());
        pay_mch_key.put("out_shop_id",params.getOut_shop_id());
        pay_mch_key.put("out_sub_mch_id",params.getOut_sub_mch_id());
        pay_mch_key.put("out_mch_id",params.getOut_mch_id());
        request_content.put("pay_mch_key",pay_mch_key);

        request_content.put("nonce_str",PayUtil.getRandomStringByLength(20));

        JSONObject freeze_content = new JSONObject();
        freeze_content.put("author_code",params.getAuthor_code());
        freeze_content.put("body",PayUtil.getRandomStringByLength(10));
        freeze_content.put("out_freeze_no",params.getOut_freeze_no());
        freeze_content.put("freeze_fee",params.getFreeze_fee());
        freeze_content.put("fee_type","CNY");
        request_content.put("freeze_content",freeze_content);

        JSONObject order_client = new JSONObject();
        order_client.put("terminal_type",3);
        order_client.put("sdk_version",1.0);
        order_client.put("device_id",params.getDevice_id());
        order_client.put("spbill_create_ip",ipAddr);
        request_content.put("order_client",order_client);

        paramObject.put("request_content",JSON.toJSONString(request_content));

        log.info("扫码押金冻结参数："+JSON.toJSONString(paramObject));
        String result = null;
        try {
            result = HttpClientUtils.post("https://pay.qcloud.com/cpay/scancode_freeze", JSON.toJSONString(paramObject),"UTF-8");
            if(StringUtils.isBlank(result)){
                return Result.fail("扫码押金冻结异常");
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            Object response_content = jsonObject.get("response_content");
            JSONObject reJsonObject = JSONObject.parseObject(JSON.toJSONString(response_content));
            String status = (String)reJsonObject.get("status");
            if("0".equals(status)){
                return Result.success("扫码押金冻结成功");
            }else{
                return Result.fail("扫码押金冻结异常:"+reJsonObject.get("description"));
            }
        }catch (Exception e){
            log.error("扫码押金冻结异常：",e);
            return Result.fail(e.getMessage());
        }
    }

}
